package com.wang.mandkey.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.wang.common.http.HttpCallBack;
import com.wang.common.http.HttpRequesterTask;
import com.wang.mandkey.App;
import com.wang.mandkey.R;
import com.wang.mandkey.bean.AdBean;
import com.wang.mandkey.bean.GridViewAdapter;
import com.wang.mandkey.net.Connecter;
import com.wang.mandkey.net.ConnecterPool;
import com.wang.mandkey.parser.AdBeanParser;
import com.wang.mandkey.tool.MediaTool;
import com.wang.mandkey.tool.SeariesTool;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.ProjectEnvironment;
import com.wang.mandkey.utils.SharePersistent;
import com.wang.mandkey.utils.StringUtils;
import com.waps.AdInfo;
import com.waps.AppConnect;
import com.waps.MiniAdView;

/**
 * 这是主activity
 * 
 * @author wangzy
 * 
 */
public class MainActivity extends BaseActivity implements
/* ViewFactory, */View.OnClickListener {

	// private TextSwitcher textSwitcherAd;
	private String tag = "MainActivity";
	private List<AdBean> mArrayListAdbean = ProjectEnvironment.arrayListAdBeanDefault;

	private final int INT_HANDLER_AD = 100;
	private int mIntAdIndex = -1;// 等于-1使用默认的广告bean

	private GridView mGridView;
	private int INT_TOOL_COUNT = 6;

	// private final int INT_TOOL_HOW=0;
	// private final int INT_TOOL_LINK_SET=1;
	private final int INT_TOOL_KEYBORAD = 0;
	private final int INT_TOOL_MOUSE = 1;
	private final int INT_TOOL_PPT = 2;
	private final int INT_TOOL_REMOTE = 3;
	private final int INT_TOOL_WEIBO = 4;
	private final int INT_TOOL_HELP = 5;

	private Button mButtonLinkHost;
	private Button mButtonGetPc;
	private Button mButtonAgree, mButtonNegative;
	private ImageButton mButtonImage;
	private String STRING_KEY_NOTIFY = "key_notify";

	public final int INT_GO_BOX = 100;
	public final int INT_GO_SHARE = 101;
	private String redirectUri = "http://www.tencent.com/zh-cn/index.shtml";

	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP KEY
	private String clientId = "801115505";
	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP SECRET
	private String clientSecret = "be1dd1410434a9f7d5a2586bab7a6829";

	private OAuthV2 oAuth;

	private boolean initOver = false;

	private View exitView;

	private CountDownLatch countDownLath;

	private AdInfo mAdInfo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		oAuth = new OAuthV2(redirectUri);
		oAuth.setClientId(clientId);
		oAuth.setClientSecret(clientSecret);

		// 关闭OAuthV2Client中的默认开启的QHttpClient。
		OAuthV2Client.getQHttpClient().shutdownConnection();
		setUpView();
		initScreenSize();
		countDownLath = new CountDownLatch(1);
		Tool.showWifiStrenth(this);
		MediaTool.addLoadListener(this);
		InitTask ast = new InitTask();
		ast.start();
	}

	public void setUpView() {
		setContentView(R.layout.main);

		mGridView = (GridView) findViewById(R.id.gridViewTools);
		String[] descs = new String[INT_TOOL_COUNT];

		// descs[INT_TOOL_HOW]= "如何使用";
		descs[INT_TOOL_KEYBORAD] = "无线手柄";
		descs[INT_TOOL_MOUSE] = "无线鼠标";
		descs[INT_TOOL_PPT] = "ppt助手";
		descs[INT_TOOL_REMOTE] = "远程工具";
		descs[INT_TOOL_WEIBO] = "微博分享";
		descs[INT_TOOL_HELP] = "神奇盒子";

		int[] drables = new int[INT_TOOL_COUNT];

		// drables[INT_TOOL_HOW]=R.drawable.main_how;
		drables[INT_TOOL_KEYBORAD] = R.drawable.main_keyboard;
		drables[INT_TOOL_MOUSE] = R.drawable.main_mouse;
		drables[INT_TOOL_PPT] = R.drawable.main_ppt;
		drables[INT_TOOL_REMOTE] = R.drawable.main_remote_tool;
		drables[INT_TOOL_WEIBO] = R.drawable.main_weibo;
		drables[INT_TOOL_HELP] = R.drawable.magicbox;

		mButtonLinkHost = (Button) findViewById(R.id.buttonLinkHost);
		mButtonLinkHost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// SharePersistent.savePerference(GetPcActivity.this,
				// ProjectEnvironment.STRING_KEY_NOTIFY, "1");
				String key2Setting = SharePersistent
						.getPerference(MainActivity.this,
								ProjectEnvironment.STRING_KEY_NOTIFY);
				if (!StringUtils.isEmpty(key2Setting)
						&& "1".equals(ProjectEnvironment.STRING_VALUE_NOTIFY)) {
					startOtherActivity(SettingActivity.class);
				} else {
					startOtherActivity(GetPcActivity.class);
				}
			}
		});

		mButtonGetPc = (Button) findViewById(R.id.buttonGetPc);
		mButtonGetPc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Tool.mkdir("/sdcard/无线鼠盘");
					Tool.copyAssetFile2Sdcard(MainActivity.this, "pc.zip",
							"/sdcard/无线鼠盘/");
					Toast.makeText(MainActivity.this,
							"拷贝完成,请把sd卡'无线鼠盘'文件下面内容拷贝到电脑后使用!",
							Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					e.printStackTrace();
					Log.e(tag, "e:" + e.toString());
					Toast.makeText(MainActivity.this, "拷贝失败，请检查是否插好sdk卡！",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		GridViewAdapter gridAdapter = new GridViewAdapter(this, descs, drables);
		mGridView.setAdapter(gridAdapter);

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int p,
					long arg3) {
				Connecter ckm = ConnecterPool
						.getConnectorByKey(ConnecterPool.STRING_CKEY);
				view.startAnimation(AnimationUtils.loadAnimation(
						MainActivity.this, R.anim.fadescale_in));
				switch (p) {
				/*
				 * case INT_TOOL_HOW: Tool.startOtherActivity(MainActivity.this,
				 * GuiderActivity.class); break;
				 */
				case INT_TOOL_KEYBORAD:
					if (null == ckm) {
						notifyNoNet();
						return;
					} else {

						ArrayList<String> caselist = SeariesTool
								.loadCaseList(MainActivity.this);
						if (null == caselist || caselist.isEmpty()) {
							startOtherActivity(KeyBoardActivity.class);
						} else {
							startOtherActivity(Forward2KeyBoardActivity.class);
						}
					}
					break;
				case INT_TOOL_MOUSE:
					if (null == ckm) {
						notifyNoNet();
						return;
					} else {
						Tool.startOtherActivity(MainActivity.this,
								MouseSelectedActivity.class);
					}
					break;
				case INT_TOOL_PPT:

					if (null == ckm) {
						notifyNoNet();
						return;
					} else {
						Tool.startOtherActivity(MainActivity.this,
								PptAssistantActivity.class);
					}
					break;
				case INT_TOOL_REMOTE:
					if (null == ckm) {
						notifyNoNet();
						return;
					} else {
						Tool.startOtherActivity(MainActivity.this,
								RemoteToolActivity.class);
					}
					break;
				case INT_TOOL_WEIBO: {
					Intent intent = new Intent(MainActivity.this,
							OAuthV2AuthorizeWebView.class);// 创建Intent，使用WebView让用户授权
					intent.putExtra("oauth", oAuth);
					startActivityForResult(intent, 2);
					break;
				}

				case INT_TOOL_HELP:
					Intent i = new Intent();
					i.setClass(MainActivity.this, BoxActivity.class);
					startActivity(i);
				default:
					break;
				}

			}
		});

		mButtonImage = (ImageButton) findViewById(R.id.imageButtonHelp);
		mButtonImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Tool.startOtherActivity(MainActivity.this, HelpActivity.class);
			}
		});
		// 设置迷你广告背景颜色
		AppConnect.getInstance(this).setAdBackColor(
				Color.argb(50, 120, 240, 120));
		// 设置迷你广告广告语颜色
		AppConnect.getInstance(this).setAdForeColor(Color.YELLOW);
		// 若未设置以上两个颜色，则默认为黑底白字
		LinearLayout miniLayout = (LinearLayout) findViewById(R.id.miniAdLinearLayout);
		try {
			new MiniAdView(this, miniLayout).DisplayAd(10); // 默认10秒切换一次广告

			int[] icons = { R.drawable.push1, R.drawable.push2,
					R.drawable.push3, R.drawable.push4, R.drawable.push5,
					R.drawable.push6, R.drawable.push7, R.drawable.push8,
					R.drawable.push9, R.drawable.push10, R.drawable.push11

			};
			Random r = new Random();
			int ico = r.nextInt(icons.length);
			AppConnect.getInstance(this).setPushIcon(icons[ico]);
			AppConnect.getInstance(this).getPushAd();
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(tag, e.getMessage());
		}
	}

	public void startOtherActivity(Class claz) {
		Intent intent = new Intent();
		intent.setClass(this, claz);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {

	}

	private void initScreenSize() {
		if (App.screenHeight == 0 || App.screenWidth == 0) {
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			App.screenHeight = dm.heightPixels;
			App.screenWidth = dm.widthPixels;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == event.KEYCODE_BACK) {
			// 完全退出应用
			exitView = View.inflate(this, R.layout.exit_view, null);
			exitView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (null != mAdInfo) {
						App.getAppConnect().clickAd(mAdInfo.getAdId());
					} else {
						UpdateExitViewTask evt = new UpdateExitViewTask();
						evt.start();
					}

				}
			});
			Builder builder = new AlertDialog.Builder(this);
			builder.setView(exitView);
			builder.setCancelable(true);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							App.exitApp(MainActivity.this);
						}
					});
			builder.setNegativeButton("取消", null);

			AlertDialog dialog = builder.create();

			dialog.setTitle("离别时刻,也有惊喜...");

			dialog.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			dialog.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
					WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.show();
			UpdateExitViewTask upt = new UpdateExitViewTask();
			upt.start();

		}
		return false;
	}

	/**
	 * 更新退出View
	 * 
	 * @param adInfo
	 */
	public void updateExitView(AdInfo adInfo) {
		if (null != adInfo) {
			ImageView appImg = (ImageView) exitView.findViewById(R.id.exitImg);
			TextView tvx = (TextView) exitView.findViewById(R.id.exitTitle);
			TextView tvDesc = (TextView) exitView
					.findViewById(R.id.textViewAdDesc);
			appImg.setImageBitmap(adInfo.getAdIcon());
			tvx.setText(adInfo.getAdName());
			tvDesc.setText(adInfo.getAdText());
		}

	}

	private Handler mhandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			updateExitView(mAdInfo);
		};
	};

	/**
	 * 请求广告
	 */
	public void requestAdInfo() {

		Log.i(tag, "requestAdInfo");
		HttpCallBack<AdBean> httpCallback = new HttpCallBack<AdBean>() {

			@Override
			public void onDoing() {

			}

			@Override
			public void OnStart() {

			}

			@Override
			public void OnException(Exception e) {
				Log.e(tag, "can not get adlist:" + e.getMessage());
			}

			@Override
			public Object OnComplete(List<AdBean> alist) {
				mArrayListAdbean = alist;
				return null;
			}

		};
		HttpRequesterTask<AdBean> httpRequesterTask = new HttpRequesterTask<AdBean>(
				httpCallback, new AdBeanParser());
		httpRequesterTask.execute(ProjectEnvironment.STRING_AD_URL);
		Log.i(tag, "requestAdInfo end");
	}

	/**
	 * 提醒没有网络
	 */
	public void notifyNoNet() {
		Toast.makeText(MainActivity.this,
				getResources().getString(R.string.mouse_activity_net),
				Toast.LENGTH_LONG).show();
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.shake);
		mButtonLinkHost.startAnimation(animation);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
		super.onLoadComplete(soundPool, sampleId, status);
		MediaTool.play(sampleId);
	}

	/*
	 * 通过读取OAuthV2AuthorizeWebView返回的Intent，获取用户授权信息
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 2) {
			if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
				oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
				if (oAuth.getStatus() == 0) {
					Intent i = new Intent();
					i.putExtra("oauth", oAuth);
					i.setClass(MainActivity.this, ShareQWeiBoActivity.class);
					startActivity(i);
				}
			}
		}
	}

	/**
	 * 初始化退出视图
	 * 
	 * @author Administrator
	 * 
	 */
	class UpdateExitViewTask extends Thread {

		@Override
		public void run() {
			if (null != App.getAppConnect()) {
				try {
					countDownLath.await();
					mAdInfo = App.getAppConnect().getAdInfo();
					mhandler.sendEmptyMessage(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}

	/**
	 * 预加载任务
	 * 
	 * @author Administrator
	 * 
	 */
	class InitTask extends Thread {
		@Override
		public void run() {
			try {
				AppConnect appConnect = AppConnect
						.getInstance(MainActivity.this);
				if (null != appConnect) {
					App.setAppConnect(appConnect);
					appConnect.initAdInfo();
					initOver = true;
				}
				MediaTool.load(MainActivity.this, R.raw.slience_water);
				countDownLath.countDown();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
